//
//  DbManager.m
//  CareRingApp
//
//  Created by Linktop on 2023/8/9.
//

#import "DbManager.h"
#import "ConfigModel.h"

@implementation DbManager
{
    sqlite3 *_db;
    dispatch_queue_t _serialQueue;
}

+ (instancetype)instance {
    static DbManager *_dbManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
          // 要使用self来调用
        _dbManager = [[self alloc] init];
       
    });
    return _dbManager;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        _serialQueue = dispatch_queue_create("demodbQueue", DISPATCH_QUEUE_SERIAL);
        [self openSqlite];
    }
    return self;
}


- (void)openSqlite {

    if(_db != nil) {
        return;
    }
    //获取文件路径
//    NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *strPath = [self getDbPath];//[str stringByAppendingPathComponent:@"my.sqlite"];
    NSLog(@"%@",strPath);
    //如果数据库存在就打开,如果不存在就创建一个再打开
    int result = sqlite3_open([strPath UTF8String], &_db);
    //判断
    if (result == SQLITE_OK) {
        NSLog(@"数据库打开成功");
    } else {
        NSLog(@"数据库打开失败");
    }
}



-(void)dealloc
{
    
    if (_db) {
        sqlite3_close(_db);
    }
}
                  
                  
                  

-(NSString *)getDbPath
{
    
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path =  [[paths lastObject]stringByAppendingPathComponent:@"DemodataBase.sqlite"];
    return path;
}

-(void)dbQueue:(void(^)(sqlite3 *db))BLK {
    
    WEAK_SELF
    dispatch_async(_serialQueue, ^{
        STRONG_SELF
        if (BLK) {
            BLK(strongSelf->_db);
        }
    });
    
}


@end
